package com.anabur.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.anabur.persistent.system.User;
import com.anabur.system.AafAbstractDAO;



public class UserDAO extends AafAbstractDAO{
	
	public UserDAO(SessionFactory sessionFac){
		super(sessionFac);
	}
	
	public User findUserByName(String name) throws Exception{
		User user=null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("from User where name like :name");
			query.setString("name",name);
			user = (User) query.uniqueResult();
			sess.close();
		}catch (Exception e) {
			sess.close();
			throw e;
		}		
		return user;
	}

	protected String getNameOfPojo() {
		return User.class.getSimpleName();
	}
	
	public boolean validateUser(String name, String pass) throws Exception {
		List list=null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("from User " +
					"where name = :name and password = :pass");
			query.setString("name",name);
			query.setString("pass",pass);
			list = (List) query.list();
			sess.close();
			return !list.isEmpty();
		}catch (Exception e) {
			sess.close();
			throw e;
		}		
	}
	
	public List<User> getUsers() throws Exception {
		List list=null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("from User");
			list = (List) query.list();
			sess.close();
		}catch (Exception e) {
			sess.close();
			throw e;
		}	
		return list;
	}
	
}
